#!/bin/bash

# 1. Define the base directory
BASE_DIR="olm/components"
ARCH=$(uname -m)
# 2. Check if the base directory exists
if [ ! -d "$BASE_DIR" ]; then
  echo "Directory $BASE_DIR does not exist."
  exit 1
fi

# 3. Iterate over all subdirectories in the base directory
for component_dir in "$BASE_DIR"/*; do
  # Check if it is a directory
  if [ -d "$component_dir" ]; then
    component_name=$(basename "$component_dir")  # Get the component name

    # 4. Look for manifests directories and extract versions
    manifests_dir="$component_dir/manifests"
    if [ -d "$manifests_dir" ]; then
      # Initialize an array to hold versions
      versions=()

      # Collect versions from manifests directory
      for version_dir in "$manifests_dir"/*; do
        if [ -d "$version_dir" ]; then
          version=$(basename "$version_dir")  # Get the version number
          echo "${component_name} - version: $version"
          versions+=("$version")
        fi
      done

      # Check if any versions were found
      if [ ${#versions[@]} -eq 0 ]; then
        echo "No versions found for component $component_name"
        continue
      fi

      # Sort versions and find the highest version
      IFS=$'\n' sorted_versions=($(sort -V <<<"${versions[*]}"))
      unset IFS
      highest_version=${sorted_versions[-1]}  # The highest version is the last in the sorted array

      # 5. Generate bundle using opm
      echo "Creating bundle for component $component_name..."
      for version in "${versions[@]}"; do
        Registry_Image="registry.uniontech.com/uccps-operators/k8s-operator-bundle/$component_name-$ARCH:$version" && \
        opm alpha bundle generate \
          --directory "$manifests_dir/$version" \
          --package "$component_name" \
          --channels "$version" \
          --default "$highest_version" && \
        podman build -f bundle.Dockerfile -t $Registry_Image && \
        podman push $Registry_Image && \
        opm registry add -b $Registry_Image -d marketplace.db --container-tool podman
      done
    else
      echo "Manifests directory not found for component $component_name"
    fi
  fi
done